//
//  CGLoginViewController.m
//  SchoolClient
//
//  Created by mac on 15/10/29.
//  Copyright © 2015年 mac. All rights reserved.
//

#import "CGLoginViewController.h"
#import "AppDelegate.h"

#import "CGRegistViewController.h"
#import "CGRetrieveViewController.h"

@interface CGLoginViewController ()<UITextFieldDelegate>

@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)UITextField *accountText;            //账号
@property(nonatomic,strong)UITextField *passwordText;           //密码
@property(nonatomic,strong)UIButton *loginButton;               //登录
@property(nonatomic,assign)CGFloat textFontSize;

@property(nonatomic,strong)UIWindow *coverWindow;
@property(nonatomic,strong)UIView *shadeView;
@property(nonatomic,strong)UIActivityIndicatorView *activity;


@end

@implementation CGLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"登录";
    self.view.backgroundColor = [Tools getColor:@"ebebeb"];
    self.textFontSize = 15;
    //添加右侧注册按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"注册" style:UIBarButtonItemStylePlain target:self action:@selector(registerButtonClicked)];

    [self layoutUI];
}

-(void)layoutUI{
    
    //底部添加一个scrollowView {{0, 0}, {320, 480}}
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 220)];

    //self.scrollView.backgroundColor = [UIColor yellowColor];
    self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, 360);
    [self.view addSubview:self.scrollView];
    
    CGRect aFrame = CGRectMake(20, 30, SCREEN_WIDTH - 20 - 20, 44);
    CGRect bFrame = CGRectMake(60, 35, SCREEN_WIDTH - 40 - 40, 34);
    CGRect cFrame = CGRectMake(30, 42, 20, 20*38/37);
    //账号
    UIImageView *accountView = [[UIImageView alloc]initWithFrame:aFrame];
    accountView.image = [UIImage imageNamed:@"login_input_phone_bg"];
    [self.scrollView addSubview:accountView];
    //输入文本框
    self.accountText = [[UITextField alloc]initWithFrame:bFrame];
    self.accountText.clearButtonMode = UITextFieldViewModeAlways;
    self.accountText.placeholder = @"账号";
    self.accountText.font = [UIFont systemFontOfSize:self.textFontSize];
    [self.accountText becomeFirstResponder];
    [self.scrollView addSubview:self.accountText];
    self.accountText.delegate = self;
    //图标
    UIImageView *accountImageView = [[UIImageView alloc]initWithFrame:cFrame];
    accountImageView.image = [UIImage imageNamed:@"login_phone_icon"];
    [self.scrollView addSubview:accountImageView];
    
    //密码
    aFrame.origin.y += 60;
    bFrame.origin.y += 60;
    cFrame.origin.y += 60;
    UIImageView *passwordView = [[UIImageView alloc]initWithFrame:aFrame];
    passwordView.image = [UIImage imageNamed:@"login_input_phone_bg"];
    [self.scrollView addSubview:passwordView];
    //输入文本框
    self.passwordText = [[UITextField alloc]initWithFrame:bFrame];
    self.passwordText.clearButtonMode = UITextFieldViewModeAlways;
    self.passwordText.placeholder = @"密码";
    self.passwordText.secureTextEntry = YES;
    self.passwordText.font = [UIFont systemFontOfSize:self.textFontSize];
    [self.scrollView addSubview:self.passwordText];
    self.passwordText.delegate = self;
    //图标
    UIImageView *passwordImageView = [[UIImageView alloc]initWithFrame:cFrame];
    passwordImageView.image = [UIImage imageNamed:@"login_password_icon"];
    [self.scrollView addSubview:passwordImageView];
    
    //登录Button
    aFrame.origin.y += 80;
    self.loginButton = [[UIButton alloc]initWithFrame:aFrame];
    [self.loginButton setBackgroundImage:[UIImage imageNamed:@"login_btn_bg"] forState:UIControlStateNormal];
    [self.loginButton setTitle:@"立即登录" forState:UIControlStateNormal];
    self.loginButton.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [self.scrollView addSubview:self.loginButton];
    //添加点击事件
    [self.loginButton addTarget:self action:@selector(tapLogin:) forControlEvents:UIControlEventTouchUpInside];
    
    //忘记密码Button
    aFrame.origin.x = SCREEN_WIDTH - 100;
    aFrame.origin.y += 60;
    aFrame.size.width = 80;
    aFrame.size.height = 20;
    UIButton *passwordButton = [[UIButton alloc]initWithFrame:aFrame];
    [passwordButton setTitleColor:[Tools getColor:@"43bee0"] forState:UIControlStateNormal];
    passwordButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [passwordButton setTitle:@"忘记密码?" forState:UIControlStateNormal];
    [self.scrollView addSubview:passwordButton];
    //重新获取密码事件
    [passwordButton addTarget:self action:@selector(retrievePassword) forControlEvents:UIControlEventTouchUpInside];

    
    //添加输入框键盘收回事件
    [self.accountText addTarget:self action:@selector(nextTextField) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    [self.passwordText addTarget:self action:@selector(passwordDone) forControlEvents:UIControlEventEditingDidEndOnExit];
    
}

#pragma mark 键盘弹出/退回事件
-(void)nextTextField{
    [self.passwordText becomeFirstResponder];
}

-(void)passwordDone{
    [self.passwordText resignFirstResponder];
}


#pragma mark 登录事件
-(void)tapLogin:(UIButton *)sender{
    
    //1.手机号有效性性验证，正则表达式
    if (!self.accountText.text.length || !self.passwordText.text.length) {
        
        [Tools alertWithTitle:@"温馨提示" andMessage:@"账号或密码为空"];
        return;
    }
    
    [self popShadeView];   //开始转圈
    
    //2.发送登录请求
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"account"] = self.accountText.text;
    parameters[@"password"] = self.passwordText.text;
    
    ZYHRequest *request = [ZYHRequest new];
    [request postAsyncEncryptRequest:@"/main/login.app" parameters:parameters success:^(id responseData) {
        
        //字典转模型
        NSString *result = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"result:%@",result);
        
        if ([result rangeOfString:@"account"].location == NSNotFound) {
            
            [self hidShadeView];  //停止转圈
            [Tools alertWithTitle:@"温馨提示" andMessage:@"用户名或密码错误!"];
            return;
        }
        
        //NSLog(@"登录成功！");
        [self hidShadeView];  //停止转圈
        
        //保存数据到沙箱
        CGAccount *user = [CGAccount objectWithJSONData:responseData];
        CGAccountDefault *accountDefault = [CGAccountDefault shareAccount];
        accountDefault.user_id = user.user_id;
        accountDefault.tphone = user.tphone;
        accountDefault.account = user.account;
        accountDefault.password = user.password;
        accountDefault.login = YES;
        accountDefault.isAutoLogin = YES;
        accountDefault.isVip = user.isVip;
        
        //头像地址
        if ([result rangeOfString:@"imgPath"].location != NSNotFound) {
            accountDefault.headerIconPath = [NSString stringWithFormat:@"%@%@",BASE_URL,user.imgPath];
        }else{
            accountDefault.headerIconPath = nil;
        }
        
        //姓名
        if ([result rangeOfString:@"name"].location != NSNotFound) {
            accountDefault.name = user.name;
        }else{
            accountDefault.name = nil;
        }
        
        //学校
        if ([result rangeOfString:@"schoolName"].location != NSNotFound) {
            accountDefault.schoolName = user.schoolName;
        }else{
            accountDefault.schoolName = nil;
        }
        
        //学号
        if ([result rangeOfString:@"studentId"].location != NSNotFound) {
            accountDefault.studentId = user.studentId;
        }else{
            accountDefault.studentId = nil;
        }
        
        //学号
        if ([result rangeOfString:@"qq"].location != NSNotFound) {
            accountDefault.qq = user.qq;
        }else{
            accountDefault.qq = nil;
        }
        
        //身份证号
        if ([result rangeOfString:@"idCard"].location != NSNotFound) {
            accountDefault.idCard = user.idCard;
        }else{
            accountDefault.idCard = nil;
        }
        
        
        [accountDefault saveToSandBox];
        
        //返回上一级界面
        [self.navigationController popViewControllerAnimated:YES];

        
    } failure:^(NSError *error) {

        [self hidShadeView];  //停止转圈
        [Tools alertWithTitle:@"温馨提示" andMessage:@"网络超时,请稍后再试"];
        return;
    }];
    
}

#pragma mark 点击注册事件
-(void)registerButtonClicked{

    CGRegistViewController *registVC = [CGRegistViewController new];
    [self.navigationController pushViewController:registVC animated:YES];

}

#pragma mark 找回密码事件
-(void)retrievePassword{
    
    CGRetrieveViewController *retrieveVC = [CGRetrieveViewController new];
    [self.navigationController pushViewController:retrieveVC animated:YES];
}



#pragma mark 弹出网络延时加载框
-(void)popShadeView{
    
    self.shadeView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.shadeView.backgroundColor = [UIColor blackColor];
    self.shadeView.alpha = 0.3;
    self.coverWindow = [UIApplication sharedApplication].keyWindow;
    [self.coverWindow addSubview:self.shadeView];
    
    //添加一个等待进度轮
    self.activity = [[UIActivityIndicatorView alloc]init];
    self.activity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    self.activity.color = [UIColor blueColor];
    CGPoint center = self.loginButton.center;
    center.y += 20;
    self.activity.center = center;
    [self.activity startAnimating];
    [self.coverWindow addSubview:self.activity];
    
    [self.loginButton setTitle:@"登陆中..." forState:UIControlStateNormal];
}

#pragma mark 取消网络延时加载框
-(void)hidShadeView{
    
    self.shadeView.hidden = YES;
    [self.activity stopAnimating];
    
    [self.loginButton setTitle:@"立即登录" forState:UIControlStateNormal];
    self.passwordText.text = @"";
    
}

#pragma mark 注册键盘通知
-(void)viewWillAppear:(BOOL)animated{
    /*
     UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 480}, {320, 253}}";
     UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 227}, {320, 253}}";
     */
    [super viewWillAppear:animated];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(openKeyboard:) name:UIKeyboardDidShowNotification object:nil];
    [center addObserver:self selector:@selector(closeKeyboard:) name:UIKeyboardWillHideNotification object:nil];
    
}

//键盘弹起时
-(void)openKeyboard:(NSNotification *)notification{
    
   self.scrollView.contentSize =  CGSizeMake(SCREEN_WIDTH, 360);

}

//键盘收起时
-(void)closeKeyboard:(NSNotification*)notification{
    
    self.scrollView.contentSize =  CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT - 220);
}

@end
